package token

import (
	"crypto/rsa"
	"time"

	"github.com/dgrijalva/jwt-go"
)

type JWTTokenGen struct {
	issuer     string
	nowFunc    func() time.Time
	privateKey *rsa.PrivateKey
}

func NewJWTTokenGen(issuer string, privateKey *rsa.PrivateKey) *JWTTokenGen {
	return &JWTTokenGen{
		issuer:     issuer,
		nowFunc:    time.Now,
		privateKey: privateKey,
	}
}

func (j *JWTTokenGen) GenarateToken(accountID string, expire time.Duration) (string, error) {
	now := j.nowFunc()
	ExpiresAt := now.Add(expire)
	token := jwt.NewWithClaims(jwt.SigningMethodRS512, jwt.StandardClaims{
		Subject:   accountID,
		IssuedAt:  now.Unix(),
		ExpiresAt: ExpiresAt.Unix(),
		Issuer:    j.issuer,
	})
	return token.SignedString(j.privateKey)
}
